const log4js = require('log4js')
const log4js_extend = require("log4js-extend");
const directoryUtils = require("./directoryUtils");
const config = require("../db/config");

// 在配置 log4js 之前调用确保目录存在
directoryUtils.ensureDirectory(config.logger.path);

/**
 * 日志组件 log4js 配置
 */
log4js.configure({
    replaceConsole: true,
    appenders: {
        // 控制台输出
        stdout: { type: 'stdout'},
        // express请求日志
        request: {
            type    : 'dateFile', filename: config.logger.path+".log" , pattern : 'request-yyyy-MM-dd.log',
            alwaysIncludePattern: true,maxLogSize: 10485760, backups: config.logger.filecount , compress: true
        },
        // 错误日志
        error: {
            type    : 'dateFile', filename: config.logger.path+".log" , pattern : 'error-yyyy-MM-dd.log',
            alwaysIncludePattern: true,maxLogSize: 10485760, backups: config.logger.filecount , compress: true
        },
        // 普通日志
        info: {
            type    : 'dateFile', filename: config.logger.path+".log" , pattern : 'info-yyyy-MM-dd.log',
            alwaysIncludePattern: true,maxLogSize: 10485760, backups: config.logger.filecount , compress: true
        }
    },
    categories: {
        // appenders:取appenders项, level:设置级别
        default:    { appenders: ['stdout', 'request','info']   , level: 'debug' },
        error:      { appenders: ['stdout', 'error']            , level: 'error' },
        // sip服务使用
        sip:        { appenders: ['stdout', 'info']             , level: 'debug' },
        db:         { appenders: ['stdout', 'info']             , level: 'debug' },
        // express web服务使用
        request:    { appenders: ['stdout', 'request']          , level: 'debug'},
        media:      { appenders: ['stdout', 'info']             , level: 'debug'},
    }
});

log4js_extend(log4js, {
    path: __dirname,
    format: "at @name (@file:@line:@column)"
});

/**
 * name 取值categories里的某一键值
 */
exports.getLogger = function (name) {
    return log4js.getLogger(name || 'default')
}

/**
 * 用来与express结合,记录请求日志
 */
exports.useLogger = function (app, logger) {
    app.use(log4js.connectLogger(logger || log4js.getLogger('default'), {
        // 自定义输出格式
        format: '[:remote-addr :method :url :status :response-timems][:referrer HTTP/:http-version :user-agent]'
    }))
}
